package com.test.common.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.test.common.exception.MyException;
import com.test.common.vo.ExceptionEnum;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 获取今天天气返回json对象
 * @Author Mr.Li
 * @Date 2020/3/10 16:05
 */
@Configuration
public class GetTodayWeatherUtil {
    //根据城市获取天气信息
    //cityName 是你要取得天气信息的城市的中文名字，如“北京”，“深圳”  接收city为
    public  JSONObject getWeatherInform(String cityId){
        URL url = null;
        String inputline = "";
        String info = "";
        List<Object> list = new ArrayList<>();
        try {
            //使用get方式读取
            url = new URL("http://t.weather.sojson.com/api/weather/city/"+cityId);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            InputStreamReader inReader = new InputStreamReader(conn.getInputStream(), "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inReader);
            while((inputline = bufferedReader.readLine()) != null){
                info += inputline;
            }
            bufferedReader.close();
            // 处理json数据
            JSONObject jsonob = JSONObject.parseObject(info);
            //获取城市信息
            JSONObject cityInfo = jsonob.getJSONObject("cityInfo");
            //获取天气对象
            JSONObject data = jsonob.getJSONObject("data");

            //获取未来15天天气信息集合
            JSONArray jsonArray = data.getJSONArray("forecast");

            //获取今天天气
            JSONObject TodayWeather = jsonArray.getJSONObject(0);
            return TodayWeather;
        } catch (IOException e) {
            throw new MyException(ExceptionEnum.RESULT_IS_EMPTY);
        }


    }

}